package org.example.AQS;

import java.util.concurrent.locks.Condition;

public class 自定义AQS1 {

    // ABC三个线程 交替打印A, 每一个打印30个字符
    private static int count = 1;
    static final int MAX_COUNT = 90;
    static int currPrint = 0;
    static final int PRINT_SIZE = 3;
    static MyLock lock = new MyLock();
    static Condition c1 = lock.newCondition();
    static Condition c2 = lock.newCondition();
    static Condition c3 = lock.newCondition();

    public static void main(String[] args) {
        Runnable r1 = () -> {
            while (count <= MAX_COUNT) {
                lock.lock();
                try {
                    while (currPrint % PRINT_SIZE != 0)  c1.await();
                    if (count > MAX_COUNT) break;
                    System.out.println(count + " : A");
                    count++;
                    currPrint++;
                    c2.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        };
        Runnable r2 = () -> {
            while (count <= MAX_COUNT) {
                lock.lock();
                try {
                    while (currPrint % PRINT_SIZE != 1)  c2.await();
                    if (count > MAX_COUNT) break;
                    System.out.println(count + " : B");
                    count++;
                    currPrint++;
                    c3.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        };
        Runnable r3 = () -> {
            while (count <= MAX_COUNT) {
                lock.lock();
                try {
                    while (currPrint % PRINT_SIZE != 2)  c3.await();
                    if (count > MAX_COUNT) break;
                    System.out.println(count + " : C");
                    count++;
                    currPrint++;
                    c1.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        Thread t3 = new Thread(r3);
        t1.start();
        t2.start();
        t3.start();
    }


}
